package com.example.audiotunning;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

interface DataListener {
    void onDataReceived(String data);
    void onConnectionStatusChanged(boolean isConnected);
    void onError(String errorMessage);
}

public class SocketClient {
    private String serverHost;
    private int serverPort;
    private Socket socket;
    private OutputStream out;
    private BufferedReader in;
    private Thread receiverThread;
    private boolean isConnected = false;
    private DataListener dataListener;

    public SocketClient(String serverHost, int serverPort) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
    }

    public void setDataListener(DataListener listener) {
        this.dataListener = listener;
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void connect() {
        if (isConnected) return;

        new Thread(() -> {
            try {
                socket = new Socket(serverHost, serverPort);
                out = socket.getOutputStream();
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                isConnected = true;

                if (dataListener != null) {
                    dataListener.onConnectionStatusChanged(true);
                }

                startReceiverThread();

            } catch (IOException e) {
                isConnected = false;
                if (dataListener != null) {
                    dataListener.onError("连接失败: " + e.getMessage());
                    dataListener.onConnectionStatusChanged(false);
                }
                e.printStackTrace();
            }
        }).start();
    }

    public void disconnect() {
        if (!isConnected) return;

        new Thread(() -> {
            try {
                isConnected = false;
                if (receiverThread != null) {
                    receiverThread.interrupt();
                }
                if (in != null) in.close();
                if (out != null) out.close();
                if (socket != null) socket.close();

                if (dataListener != null) {
                    dataListener.onConnectionStatusChanged(false);
                }

            } catch (IOException e) {
                if (dataListener != null) {
                    dataListener.onError("断开连接失败: " + e.getMessage());
                }
                e.printStackTrace();
            }
        }).start();
    }

    public void sendMessage(String message) {
        if (!isConnected || out == null) {
            if (dataListener != null) {
                dataListener.onError("无法发送: 未连接到服务器");
            }
            return;
        }

        new Thread(() -> {
            try {
                byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
                out.write(bytes);
                out.flush();
            } catch (Exception e) {
                if (dataListener != null) {
                    dataListener.onError("发送消息失败: " + e.getMessage());
                }
                e.printStackTrace();
            }
        }).start();
    }
    public void sendMessage(byte[] message) {
        if (!isConnected || out == null) {
            if (dataListener != null) {
                dataListener.onError("无法发送: 未连接到服务器");
            }
            return;
        }

        new Thread(() -> {
            try {
                out.write(message);
                out.flush();
            } catch (Exception e) {
                if (dataListener != null) {
                    dataListener.onError("发送消息失败: " + e.getMessage());
                }
                e.printStackTrace();
            }
        }).start();
    }


    public void sendMessage(char[] message) {
        if (!isConnected || out == null) {
            if (dataListener != null) {
                dataListener.onError("无法发送: 未连接到服务器");
            }
            return;
        }

        new Thread(() -> {
            try {
                String str = new String(message);
                byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
                out.write(bytes);
                out.flush();
            } catch (Exception e) {
                if (dataListener != null) {
                    dataListener.onError("发送消息失败: " + e.getMessage());
                }
                e.printStackTrace();
            }
        }).start();
    }

    private void startReceiverThread() {
        receiverThread = new Thread(() -> {
            try {
                String serverMessage;
                while (isConnected && (serverMessage = in.readLine()) != null) {
                    if (dataListener != null) {
                        dataListener.onDataReceived(serverMessage);
                    }
                }
            } catch (IOException e) {
                if (isConnected && dataListener != null) {
                    dataListener.onError("接收消息失败: " + e.getMessage());
                    disconnect(); // 发生错误时断开连接
                }
                e.printStackTrace();
            }
        });

        receiverThread.start();
    }
}